package com.cloudfun.campusshare.service;

import com.cloudfun.campusshare.entity.CreatorPersistenceEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Table;

/**
 * Created by Huqin on 2020/6/5
 */
public abstract class CreatorPersistenceService implements InitializingBean {

    private String tableName;

    @PersistenceContext
    private EntityManager entityManager;

    protected abstract Class<?> getEntityClass();

    /**
     * 更新创建人名称
     *
     * @param id
     * @param name
     */
    @Transactional
    public void updateCreatorNameByCreatorId(String id, String name) {
        Query nativeQuery = entityManager.createNativeQuery("update " + this.tableName + " set creator_name=:name where creator_id=:id");
        nativeQuery.setParameter("name", name);
        nativeQuery.setParameter("id", id);
        nativeQuery.executeUpdate();
    }

    /**
     * 更新创建人
     *
     * @param id
     */
    @Transactional
    public void updateCreator(String id) {
        Query nativeQuery = entityManager.createNativeQuery("update " + this.tableName + " set creator_id=:newId where creator_id=:oldId");
        nativeQuery.setParameter("oldId", id);
        nativeQuery.setParameter("newId", null);
        nativeQuery.executeUpdate();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Class<?> entityClass = getEntityClass();
        Class<?> superclass = entityClass.getSuperclass();
        if (!superclass.equals(CreatorPersistenceEntity.class)) {
            throw new RuntimeException(entityClass.getName() + " must extends RecordCreatorEntity.class");
        }
        Table table = entityClass.getAnnotation(Table.class);
        if (null == table) {
            throw new RuntimeException(entityClass.getName() + " must be annotated with " + Table.class.getName());
        }
        String tableName = table.name();
        if (StringUtils.isBlank(tableName)) {
            throw new RuntimeException("can not resolve table name from entity: " + entityClass.getName());
        }
        this.tableName = tableName;
    }
}
